/*
Problem:    Combination Sum
Difficulty: Medium
Source:     http://www.leetcode.com/onlinejudge
Notes:
Given a set of candidate numbers (C) and a target number (T), find all unique
combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … ,ak) must be in non-descending order.
(ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
*/
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
	vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
		int* remain = (int*) malloc(sizeof(int) * candidates.size());
		sort(candidates.begin(), candidates.end(), greater<int>());
		for (int i = 0; i < candidates.size(); i++)
			remain[i] = target / candidates[i];

		vector<vector<int> > result;
		vector<int> items;
		FindPartialSum(candidates, target, remain, 0, 0, &items, &result);
		return result;
	}

	void FindPartialSum(const vector<int>& candidates, int target, int remain[], int sum, 
			int last_index, vector<int>* items, vector<vector<int> >* result) {
		if (sum == target) {
			result->push_back(*items);
			return;
		}

		for (int i = last_index; i < candidates.size(); i++) 
			if (remain[i] > 0 && sum + candidates[i] <= target) {
				remain[i]--;
				items->push_back(candidates[i]);
				FindPartialSum(candidates, target, remain, sum + candidates[i], i, items, result);
				remain[i]++;
				items->pop_back();

			}
	}
};


int main(int argc, char* argv[])
{
	int a[] = {2, 3, 6, 7};
	vector<int> input;
	for (int i = 0; i < 4; i++)
		input.push_back(a[i]);

	Solution s;	
	vector<vector<int> > result = s.combinationSum(input, 7);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++)
			cout << result[i][j] << " ";
		cout << endl;
	}
	
	return 0;
}